<?php
/**
 * 5.9版本由1号改为25号
 * 下个月将要过期的积分通知，每个月25号通知下个月即将过期的积分
 * @author yiwan
 */

//ini_set('display_errors', 1);
ini_set('memory_limit', -1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Doraemon\model\PointMonth as mPointMonth;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\Log;

$t1 = microtime(true);

$month = date('Ym', strtotime('-11 month'));

$tableNum = mPointMonth::_SUB_TABLE_NUM;
$link = Hhzurl::getDomain() . '/community/points-mall';
$link =  'niceliving://webview/fullscreen?protego=' . urlencode(base64_encode(json_encode(['url' => $link])));

for ($i = 0; $i < $tableNum; $i++) {
    $tabStar = microtime(true);
    $pageSize = 10000;
    $page = 1;
    $list = [];
    $userNum = 0;
    do {
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where = [
            'AND' => [
                'month' => $month,
                'remain_point[>=]' => 500,
            ],
            'LIMIT' => $limit
        ];
        $tstart = microtime(true);
        mPointMonth::enforceSubTableNameSuffix($i);
        $list = mPointMonth::select(['uid', 'remain_point'], $where);
        mPointMonth::resetEnforceSubTable();
        if ($list) {
            expirePointNotice($list, $i, $page, $link);
        }

        $tend = microtime(true);
        $ttime = $tend - $tstart;
        $userNum = $userNum + count($list);

        $page++;
    } while ($list);

    $tabEnd = microtime(true);
    $time = $tabEnd - $tabStar;
    Log::debug($i . '表执行完毕', ['量' => $userNum, '时' => number_format($time, 2) . 's']);
}
$t2 = microtime(true);
$time = $t2 - $t1;
$mtime = ($time * 1000) . 'ms';
Log::debug('表全部执行完毕', ['时' => number_format($time, 2) . 's ']);

function expirePointNotice($list, $i, $page, $link)
{
    foreach ($list as $row) {
        if (empty($row['uid'])) {
            continue;
        }
        $uid = $row['uid'];
        $point = $row['remain_point'];
        try {
            \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                'msgCode' => 224,
                'to_uid' => $uid,
                'msgParams' => [
                    'point' => $point,
                    'link' => $link,
                ]
            ], \Doraemon\cache\Queue::QUEUE_DORAEMON);
        } catch (Exception $e) {
            Log::debug($i . '表' . $page . '页执行出错', ['错误信息' => [$e->getMessage(), $e->getFile(), $e->getLine()]]);
        }
    }
}